package com.company.wechatpush.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.company.wechatpush.config.PushConfig;
import com.company.wechatpush.entity.Result;
import com.company.wechatpush.utils.RequestUtil;

/**
 * @author Real
 * @since 2022-09-03 1:03 AM
 */
public class LocationService {

    /**
     * 请求天行Location信息
     */
    public static final String LOCATION_URI = "http://api.tianapi.com/geoconvert/index";
    public static final String SUCCESS = "200";

    /**
     * {
     * "code": 200,
     * "msg": "success",
     * "newslist": [
     * {
     * "town_code": "310106012",
     * "direction": "附近",
     * "street": "威海路",
     * "country_code_iso2": "CN",
     * "city_level": 2,
     * "country_code": -1,
     * "country": "中国",
     * "city": "上海市",
     * "distance": "49",
     * "province": "上海市",
     * "adcode": "310106",
     * "street_number": "289弄-2-14号",
     * }
     * }
     *
     * @param latitude
     * @param longitude
     * @return
     */
    public static Result<String> getLocationCode(String latitude, String longitude) {
        String httpUrl = LOCATION_URI + "?key=" + PushConfig.getTxKey() + "&lng=" + longitude + "&lat=" + latitude;
        String jsonResult = RequestUtil.request(httpUrl);
        JSONObject jsonObject = JSONObject.parseObject(jsonResult);
        String code = jsonObject.getString("code");
        if (!SUCCESS.equals(code)) {
            return Result.error(500, "区号请求失败，信息：" + jsonResult);
        }
        JSONArray newsList = jsonObject.getJSONArray("newslist");
        JSONObject data = newsList.getJSONObject(0);
        String adcode = data.getString("adcode");
        return Result.success(adcode);
    }

}
